﻿using System;
using System.Collections.Generic;

namespace SimpleWorkflow.Event
{
    public class EventSurrogates
    {
        private readonly Dictionary<string, WeakEvent> _weakEvents = new Dictionary<string, WeakEvent>();

        public void Publish(string name, ref EventHandler handler)
        {
            var weakEvent = new WeakEvent {Name = name};
            handler += weakEvent.Fire;
            _weakEvents[name] = weakEvent;
        }

        public void Subscribe(string name, EventHandler handler)
        {
            WeakEvent weakEvent;
            if (!_weakEvents.TryGetValue(name, out weakEvent))
                throw new ArgumentNullException("WeakEvent not published: " + name);
            weakEvent.Add(handler);
        }

        public void Unsubscribe(string name, EventHandler handler)
        {
            WeakEvent weakEvent;
            if (!_weakEvents.TryGetValue(name, out weakEvent))
                throw new ArgumentNullException("WeakEvent not published: " + name);
            weakEvent.Remove(handler);
        }
    }
}
